package com.distribute.distributelock.common.lock;

import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;

/**
 * @description:
 * @author: 刘帅
 * @time: 2020/5/14 12:31
 * 增加超时时间, 防止持有锁的客户端挂了， 导致锁释放不了
 */
public class LockCase2 extends RedisLock{

    public LockCase2(Jedis jedis, String lockKey) {
        super(jedis, lockKey);
    }

    @Override
    public void sleepBySecond(int second) {
        super.sleepBySecond(second);
    }

    @Override
    public void lock() {
        //自旋锁等待锁释放， 适用于任务时间短，否则大量的 自选浪费CPU
        while (true) {
            String result = jedis.set(lockKey, "value", "NX", "EX", 3000);
            if ("OK".equals(result)) {
//                System.out.println(Thread.currentThread().getId() + "加锁成功");
                break;
            }
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        super.lockInterruptibly();
    }

    @Override
    public boolean tryLock() {
        return super.tryLock();
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return super.tryLock(time, unit);
    }

    @Override
    public void unlock() {
        jedis.del(lockKey);
    }

    @Override
    public Condition newCondition() {
        return super.newCondition();
    }
}
